package com.zyx.utils;

import org.springframework.util.StringUtils;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;


/**
 * 日期、时间工具类
 * @author DQing
 *
 */
public class DateTimeUtil{

	/** 时间格式(yyyy-MM-dd) */
	public final static String DATE_PATTERN = "yyyy-MM-dd";
	/** 时间格式(yyyyMMdd) */
	public final static String DATE_SHORT_PATTERN = "yyyyMMdd";
	/** 时间格式(HHmmss) */
	public final static String TIME_SHORT_PATTERN = "HHmmss";
	/** 时间格式(yyyy-MM-dd HH:mm:ss) */
	public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
	public static final String LOCAL_EN = "en";
	public static final String LOCAL_CH = "ch";
	
	public static String getDateString() {
		SimpleDateFormat fm = new SimpleDateFormat(DATE_SHORT_PATTERN);
		return fm.format(new Date());
	}
	
	public static String getTimeString() {
		SimpleDateFormat fm = new SimpleDateFormat(TIME_SHORT_PATTERN);
		return fm.format(new Date());
	}
	
	
	public static String getYtDateString(){
		Calendar   rightNow   =   Calendar.getInstance(); 
		GregorianCalendar   gc1   =   new   GregorianCalendar(rightNow.get(Calendar.YEAR),   rightNow.get(Calendar.MONTH), 
		rightNow.get(Calendar.DAY_OF_MONTH)); 
		gc1.add(Calendar.DATE,   -1); 
		Date   d1   =   (Date)gc1.getTime();
		SimpleDateFormat fm = new SimpleDateFormat(DATE_SHORT_PATTERN);
		return fm.format(d1);
	}

	public static String getAnyDateString(int calType, int num){
		Calendar   rightNow   =   Calendar.getInstance(); 
		GregorianCalendar   gc1   =   new   GregorianCalendar(rightNow.get(Calendar.YEAR),   rightNow.get(Calendar.MONTH), 
				rightNow.get(Calendar.DAY_OF_MONTH)); 
		gc1.add(calType,   num); 
		Date   d1   =   (Date)gc1.getTime();
		SimpleDateFormat fm = new SimpleDateFormat(DATE_SHORT_PATTERN);
		return fm.format(d1);
	}
	

	public static String date8(){
		return date8(new Timestamp(System.currentTimeMillis()));
	}
	public static String date8(Timestamp t){
		return formatTimestamp2String(t,"yyyyMMdd");
	}
	public static String time6(){
		return time6(new Timestamp(System.currentTimeMillis()));
	}
	public static String time6(Timestamp t){
		return formatTimestamp2String(t,"HHmmss");
	}
	
	public static String getDateTime14(Date date){
		return getDateTime(date,"yyyyMMddHHmmss");
	}
	public static String getDateTime(Date date,String pattern){
		DateFormat format = new SimpleDateFormat(pattern);
		return format.format(date);
	}
	public static String getDateTime14(){
		return getDateTime14(new Date());
	}

	public static String formatDateStr2Str(String date, String format){
		if (StringUtils.isEmpty(date)){
			return "";
		}
		SimpleDateFormat fm = new SimpleDateFormat("yyyyMMdd");
		SimpleDateFormat fm1 = new SimpleDateFormat(format);
		Date d;
		try
		{
			d = fm.parse(date);
		}
		catch (ParseException e)
		{
			e.printStackTrace();
			return "";
		}
		
		return fm1.format(d);
	}
	
	/**
	 * 格式化时间戳为字符串
	 * @param date
	 * @param format
	 * @return
	 */
	public static String formatTimestamp2String(Timestamp date,String format){
		if(null==date){
			return null;
		}
		if(null==format||("").equals(format)){
			return null;
		}
		return new SimpleDateFormat(format).format(date);
	}
	/**
	 * 格式化Date为字符串
	 * @param date
	 * @param format
	 * @return
	 */
	public static String formatTimestamp2String(Date date,String format){
		if(null==date){
			return null;
		}
		if(null==format||("").equals(format)){
			return null;
		}
		return new SimpleDateFormat(format).format(date);
	}
	/**
	 * 格式化字符串为时间戳
	 * @param date
	 * @param format
	 * @return
	 */
	public static Timestamp formatString2Timestamp(String date,String format){
		if(null==date||("").equals(date)){
			return null;
		}
		if(null==format||("").equals(format)){
			return null;
		}
		return new Timestamp(formatStringToDate(date,format).getTime());
	}
	
	/**
	 * 将日期格式的字符串转换为日期
	 * @param date 源日期字符串
	 * @param format 源日期字符串格式
	 */
	public static Date formatStringToDate(String date,String format){
		if(null==date||("").equals(date)){
			return null;
		}
		if(null==format||("").equals(format)){
			return null;
		}
		SimpleDateFormat format2 = new SimpleDateFormat(format);
		try{
			Date newDate = format2.parse(date);
			return newDate;
		}catch(Exception ex){
			throw new RuntimeException(ex.getMessage());
		}
	}
	
	public static Timestamp addDay(Timestamp date,int day){
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DATE, day);
		return new Timestamp(cal.getTimeInMillis());
	}
	/**
	 * 将日期格式的字符串格式化成指定的日期格式
	 * @param dateStr 源日期字符串
	 * @param formatStr1 源日期字符串日期格式
	 * @param formatStr2 新日期字符串日期格式
	 */
	public static String formatDateStringToString(String dateStr,String formatStr1,String formatStr2){
		SimpleDateFormat format = new SimpleDateFormat(formatStr1);
		SimpleDateFormat format2 = new SimpleDateFormat(formatStr2);
		try{
			if(null==dateStr||("").equals(dateStr)){
				return "";
			}
			Date date = format.parse(dateStr);
			return format2.format(date);
		}catch(Exception ex){
			ex.printStackTrace();
			return "";
		}
	}
	
	/**
	 * yyyyMMdd 与 yyyy-MM-dd日期格式转换
	 * @param date
	 * @return
	 * @throws ParseException
	 */
	public static String dateFormate(String date, String regex){
		SimpleDateFormat sdf_sim = new SimpleDateFormat("yyyyMMdd");
		SimpleDateFormat sdf_more = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdf_target = new SimpleDateFormat(regex);
		try{
			if(date==null || "".equals(date)){
				return "";
			}else if(date.contains("-")){
				return sdf_target.format(sdf_more.parse(date));
			}else{
				return sdf_target.format(sdf_sim.parse(date));
			}
		}catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	public static String formatDataToString(Date date,String format){
		//Date类型转换为String
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		String nowTime = sdf.format(date);
		return nowTime;
	}
	
	public static Date formateStringToDate(String date){
		//String类型转换为Date
		String[] a = date.split("[-]");
		Date d = new Date(Integer.parseInt(a[0]),Integer.parseInt(a[1]),Integer.parseInt(a[2]));
		return d;
	}
	
	
	
	/***
	* 计算2个日期之间的天数
	* @param beginTime
	* @param endTime
	* @return 相差的天数
	 * @throws ParseException 
	*/
	public float getDate(String beginTime,String endTime) throws ParseException 
	{
	SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
	
	Date begin = s.parse(beginTime);
	Date end = s.parse(endTime);
	float time = (end.getTime()-begin.getTime())/1000/60/60/24;
	return time;	
	}
	
	/**
	 * 122221转换成12:22:21
	 * 
	 * @param time
	 * @return
	 */
	public static String time6(String time) {
		if (null == time){
			return null;
		}
		time = time.trim();
		if (time.length() != 6){
			return time;
		}else{
			return time.substring(0, 2) + ":" + time.substring(2, 4) + ":"
					+ time.substring(4, 6);
		}

	}	
	
	/**
	 * 格式化时间
	 * @param date
	 * @param regex
	 * @return
	 */
	public static String formatDate(Date date, String regex) {
		if(null == date){
			return null;
		}
		String s = new SimpleDateFormat(regex).format(date);
		return s;
	}	
	
	public static String format(Date date) {
        return format(date, DATE_PATTERN);
    }

    public static String format(Date date, String pattern) {
        if(date != null){
            SimpleDateFormat df = new SimpleDateFormat(pattern);
            return df.format(date);
        }
        return null;
    }
    /**
	 * getDateStr: 格式化日期字符串
	 * @param str	源日期字符串
	 * @param local	地域模式
	 * @return	String
	 */
	public static String getDateStr(String str, String local){
		if(str==null || str.length() != 8){
			return "";
		}
		String y = str.substring(0, 4);
		String m = str.substring(4, 6);
		String d = str.substring(6, 8);
		
		if(local.equals(LOCAL_EN)){
			return y+"/"+m+"/"+d;
		}else if(local.equals(LOCAL_CH)){
			return y+"年"+m+"月"+d+"日";
		}else{
			return y+"年"+m+"月"+d+"日";
		}
	}
	
	/**
	 * getTimeStr: 格式化时间字符串
	 * @param str	源时间字符串
	 * @param local	地域模式
	 * @return	String
	 */
	public static String getTimeStr(String str, String local){
		if(str==null || str.length() != 6){
			return "";
		}
		String h = str.substring(0, 2);
		String m = str.substring(2, 4);
		String s = str.substring(4, 6);
		if(local.equals(LOCAL_EN)){
			return h+":"+m+":"+s;
		}else if(local.equals(LOCAL_CH)){
			return h+"时"+m+"分"+s+"秒";
		}else{
			return h+"时"+m+"分"+s+"秒";
		}
	}
	
	/**
	 * getDateTimeStr: 格式化日期时间字符串
	 * @param str	源日期时间字符串
	 * @param local	地域模式
	 * @return	String
	 */
	public static String getDateTimeStr(String str, String local){
		if(str==null || str.length() != 14){
			return "";
		}
		String dataStr = str.substring(0, 8);
		String timeStr = str.substring(8, 14);
		
		return getDateStr(dataStr, local) + " " + getTimeStr(timeStr, local);
	}
	
	
	
	/**
	 * dateTimeStr2FormatStr: 日期字符串格式转换
	 * 
	 * 	字母  日期或时间元素  				表示  	示例  
	 *	G  	 	Era 标志符  				Text  	AD  
	 *	y  		年  Year  				1996; 	96  
	 *	M  		年中的月份  				Month  	July; Jul; 07  
	 *	w  		年中的周数  				Number  27  
	 *	W  		月份中的周数  				Number  2  
	 *	D  		年中的天数  				Number  189  
	 *	d  		月份中的天数  				Number  10  
	 *	F  		月份中的星期  				Number  2  
	 *	E  		星期中的天数  				Text  	Tuesday; Tue  
	 *	a  		Am/pm 标记  				Text  	PM  
	 *	H  		一天中的小时数（0-23） 		Number  0  
	 *	k  		一天中的小时数（1-24） 		Number  24  
	 *	K  		am/pm 中的小时数（0-11）  	Number  0  
	 *	h  		am/pm 中的小时数（1-12）  	Number  12  
	 *	m  		小时中的分钟数  			Number  30  
	 *	s  		分钟中的秒数  				Number  55  
	 *	S  		毫秒数  					Number  978  
	 * 
	 * @param dateTime	源日期字符串
	 * @param formatOld	源日期字符串格式
	 * @param formatNew	转换后的日期字符串格式
	 * @return
	 */
	public static String dateTimeStr2FormatStr(String dateTime, String formatOld, String formatNew){
		
		if(dateTime==null || dateTime.length()!=formatOld.length()){
			return "";
		}
		
		String newFormatStr = new String();
		
		SimpleDateFormat sdf_old = new SimpleDateFormat(formatOld);
		SimpleDateFormat sdf_new = new SimpleDateFormat(formatNew);
		
		try{ 
			Date date = sdf_old.parse(dateTime);
			newFormatStr = sdf_new.format(date);
		}
		catch(Exception px){
			px.printStackTrace();
		}
		
		return newFormatStr;
	}
	
	public static String getFormatSimpleByDate(Date dateTime,String formatStr){
		SimpleDateFormat format = new SimpleDateFormat(formatStr);
		if(dateTime==null){
			return "";
		}
		String formatDateStr = "";
		try{
			formatDateStr = format.format(dateTime);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return formatDateStr;
	}
	
	/**
	 * @Description：(得到已知时间的Date的前几天或后几天时间) 
	 * <p>创建人：shumin.zhang ,  2015-11-9  下午03:25:50</p>
	 * <p>修改人：shumin.zhang ,  2015-11-9  下午03:25:50</p>
	 *
	 * @param dateStr  --给定的时间串
	 * @param num
	 * @return
	 * @throws ParseException
	 * Date
	 */
	public static String getAddDayOrSubDayDateByDateStr(String dateStr ,int num) throws ParseException{
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(dateFormat.parse(dateStr));
		calendar.add(Calendar.DAY_OF_YEAR, num);
		return dateFormat.format(calendar.getTime());
	}
	
	
	/**
	 * @Description：获取num之后的日期
	 * <p>创建人：hp ,  2017-8-9  下午6:14:29</p>
	 * <p>修改人：hp ,  2017-8-9  下午6:14:29</p>
	 *
	 * @param date
	 * @param num
	 * @return
	 * @throws ParseException
	 * Date 
	 */
	public static Date getDateAfter(Date date ,int num) throws ParseException{
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_YEAR, num);
		return calendar.getTime();
	}
	
	/**
	 * @Description：字符串转date
	 * <p>创建人：hp ,  2017-8-10  下午2:51:26</p>
	 * <p>修改人：hp ,  2017-8-10  下午2:51:26</p>
	 *
	 * @param date
	 * @param format
	 * @return
	 * @throws ParseException
	 * Date 
	 */
	public static Date formateString2Date(String date ,String format) throws ParseException{
		SimpleDateFormat dateFormat = new SimpleDateFormat(format);
		return dateFormat.parse(date);
	}


	/**
	 * 设置时间格式，将该时间格式的时间转换为时间戳
	 * @param s
	 * @return
	 * @throws Exception
	 */
	public static Long dateToStamp(String s){
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_TIME_PATTERN);
		try{
			Date date = simpleDateFormat.parse(s);
			long time = date.getTime();
			return time;
		}catch (Exception e){
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 将时间戳转换为时间
	 * 将时间调整为yyyy-MM-dd HH:mm:ss时间样式
	 * @param lt
	 * @return
	 * @throws Exception
	 */
	public static String stampToTime(Long lt) throws Exception{
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_TIME_PATTERN);
		try{
			Date date = new Date(lt);
			String res = simpleDateFormat.format(date);
			return res;
		}catch (Exception e){
			e.printStackTrace();
			return null;
		}
	}
}
